<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\controller\Base;
use Firebase\JWT\JWT;
use Icharle\Wxtool\Wxtool;
use think\facade\Db;

class User extends Base
{
    public function login()
    {
        $result = $this->validate(
            $data = [
                "code" => $this->request->param('code'),
            ],
            $rule = [
                "code" => "require",
            ],
            $msg = [
                "code" => "code不能为空",
            ]
        );
        if (true !== $result) {
            // 验证失败 输出错误信息
            return jsonReturn([], '参数不完整', 400);
        }

        $a = new Wxtool();
        $code = $data['code']; //wx.login获取
        $res = $a->GetSessionKey($code);  //获取用户openid 和 session_key
        if($res && isset($res['openid'])) {
            $saveData['openid'] = $res['openid'];
            $isUser = Db::name('member_user')
                ->where('openid',$res['openid'])
                ->find();
            if($isUser){
                $userId = $isUser['id'];
                //添加登录次数
                Db::name('member_user')
                    ->where('id', $userId)
                    ->update(['login_num' => $isUser['login_num']+1]);
            }else{
                $userId = Db::name('member_user') ->insertGetId($saveData);
            }
            //生成token
            $secret = config('app.app_secret');
            if($secret){
                $token = JWT::encode(
                    [
                        'uid' => $userId,
                        'exp' => time()+7200,
                        'iat' => time(),
                        'admin' => true
                    ], $secret
                );
                return jsonReturn(['token'=>$token], 'ok', 200);
            }else{
                return jsonReturn([], '未设置密钥', 400);
            }
        }else{
            return jsonReturn([], $res['msg'], 400);
        }
    }
}
